import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/rong_im_message_event.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_keys_constant.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/websocket_manage/websocket_handler.dart';
import 'package:star_author/views/stream/dialog/evaluate_anchor_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

import '../../config/base_configuration.dart';
import '../../model/channel.dart';
import '../../utils/live_permission_util.dart';
import '../../utils/rouces_util.dart';
import '../../widgets/cover_widget.dart';
import 'stream_rtc.dart';

StreamCountsNotifier valueNotifier = StreamCountsNotifier(StreamCounts(0, 0));

class StreamCounts {
  int user_count = 0;

  int view_count = 0;

  StreamCounts(user_count, view_count);
}

class StreamCountsNotifier extends ValueNotifier<StreamCounts> {
  StreamCountsNotifier(StreamCounts streamCounts) : super(streamCounts);

  setCount(viewCount) async {
    if (viewCount != value.view_count) {
      value.view_count = viewCount;
      notifyListeners();
    }
  }
}

class StreamRtcTop extends StatefulWidget {
  late ChannelModel model;
  Function? callBack;
  LiveForm liveForm;
  bool isClear;

  StreamRtcTop(
      {Key? key,
      required this.model,
      this.callBack,
      this.isClear: false,
      this.liveForm: LiveForm.List})
      : super(key: key);

  @override
  State<StreamRtcTop> createState() => _StreamRtcTopState();
}

class _StreamRtcTopState extends State<StreamRtcTop> {
  late StreamSubscription<RongIMMessageEvent> _rongIMMessageEvent;

  bool isShowEvaluateAnchorTipView = false;

  int score = 0; //评分

  Map studioMap = {};

  String avatarImage = '';

  String anchorName = '';

  @override
  void initState() {
    super.initState();

    valueNotifier.addListener(update);
    if (StreamConf.channelModel?.living_anchor.isNotEmpty ?? false) {
      avatarImage = StreamConf.channelModel!.living_anchor['avatar'] ?? '';
      anchorName = StreamConf.channelModel!.living_anchor['nickname'] ?? '';
    } else {
      avatarImage = StreamConf.channelModel!.avatar;
      anchorName = StreamConf.channelModel!.name;
    }

    getStudioDetail();

    _rongIMMessageEvent =
        GlobalEventBus().bus.on<RongIMMessageEvent>().listen((event) async {
      if (event.message.content is TextMessage) {
        TextMessage msg = event.message.content as TextMessage;
        Map map = json.decode(msg.extra!);
        if (map.isNotEmpty) {
          if (map['operation'] == OperationKey.change_anchor) {
            getStudioDetail();
          }
        }
      }
    });
  }

  ///获取直播间信息
  getStudioDetail() async {
    await HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${StreamConf.liveId}',
      isLoading: false,
      isErrorToast: false,
    ).then((res) {
      studioMap = res.data;
      if (studioMap['living_anchor'] != null) {
        avatarImage = studioMap['living_anchor']['avatar'] ?? '';
        anchorName = studioMap['living_anchor']['nickname'] ?? '';
        isShowEvaluateAnchorTipView = SpUtil.getBool(
            SpKeysConstant.is_show_evaluate_anchor_tip_view,
            defValue: true)!;
      }
      update();
    });
  }

  void update() {
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    valueNotifier.removeListener(update);
    _rongIMMessageEvent.cancel();
  }

  @override
  void didUpdateWidget(covariant StreamRtcTop oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    if (oldWidget.isClear != widget.isClear) {
      if (mounted) setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isClear) return Container();
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Color(0x4D000000),
                  borderRadius: BorderRadius.circular(19.w),
                ),
                padding: EdgeInsets.only(
                  left: 5.0.w,
                  right: 15.0.w,
                ),
                height: 38.0.w,
                child: Row(
                  children: [
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        openEvaluateAnchorSheet();
                      },
                      child: buildCircleCover(size: 30.w, cover: avatarImage),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        left: 4.0.w,
                      ),
                      height: 38.0.w,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "${anchorName.length >= 10 ? anchorName.substring(0, 9) + "..." : anchorName}",
                            style: TextStyle(
                                fontSize: 12.0.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500),
                          ),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              RoucesUtil.getAssetsIcon('ic_live_fire_lt', 12),
                              SizedBox(
                                width: 4.w,
                              ),
                              Text(
                                "${getLiveHeat(valueNotifier.value.view_count)}",
                                style: TextStyle(
                                    fontSize: 8.0.sp, color: Colors.white),
                              ),
                            ],
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
              Row(
                children: [
                  InkWell(
                    child: Center(
                      child: Image.asset(
                        "images/ic_live_service.png",
                        width: 30.0.w,
                        height: 30.0.w,
                        fit: BoxFit.cover,
                      ),
                    ),
                    onTap: () {},
                  ),
                  SizedBox(
                    width: 20.w,
                  ),
                  Visibility(
                    child: InkWell(
                      child: Center(
                        child: Image.asset(
                          "images/live_narrow.png",
                          width: 30.0.w,
                          height: 30.0.w,
                          fit: BoxFit.cover,
                        ),
                      ),
                      onTap: () {
                        StreamConf.isShowVideo = true;
                        if (Platform.isAndroid) {
                          LivePermissionUtil.checkSystemAlertWindowPermission(
                              (isGranted) {
                            if (isGranted) {
                            } else {
                              StreamConf.uid = -1;
                            }
                            Get.back();
                          });
                        } else {
                          Get.back();
                        }
                      },
                    ),
                    visible: StreamConf.uid != -1,
                  ),
                  SizedBox(
                    width: 20.w,
                  ),
                  InkWell(
                    child: Center(
                      child: Image.asset(
                        "images/live_close.png",
                        width: 30.0.w,
                        height: 30.0.w,
                        fit: BoxFit.cover,
                      ),
                    ),
                    onTap: () async {
                      StreamConf.isShowVideo = false;
                      StreamConf.uid = -1;
                      StreamConf.isJoinRongCould = true;
                      await RongUtil.quitChatRoom();
                      WebSocketHandle.unSubscribeLiveChannel();
                      StreamConf.barrages = [];
                      widget.callBack!();
                    },
                  ),
                ],
              )
            ],
          ),
          if (isShowEvaluateAnchorTipView)
            Container(
              margin: EdgeInsets.only(top: 10.w),
              child: Stack(
                children: [
                  Image.asset(
                    "images/bg_evaluate_anchor_tip.png",
                    height: 36.w,
                    width: 285.w,
                  ),
                  Positioned(
                    bottom: 5.w,
                    left: 0,
                    right: 0,
                    child: Container(
                      alignment: Alignment.center,
                      child: Text(
                        "点击主播头像可对主播本场直播进行评价",
                        style: TextStyle(
                          color: Color(0xff5D3613),
                          fontSize: 14.sp,
                        ),
                      ),
                    ),
                  ),
                  Positioned(
                    top: 0,
                    right: 0,
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        closeTip();
                      },
                      child: Container(
                        width: 20.w,
                        height: 20.w,
                      ),
                    ),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  void closeTip() {
    isShowEvaluateAnchorTipView = false;
    SpUtil.putBool(SpKeysConstant.is_show_evaluate_anchor_tip_view, false);
    update();
  }

  //本地缓存一下 提交成功后赋值 因为服务器有缓存 暂时这样做
  bool haveReview = false;

  void openEvaluateAnchorSheet() async {
    if (studioMap['living_anchor'] != null) {
      closeTip();
      await HttpUtil.commonRequest(
        Get.context!,
        '/api/v1/studios/${StreamConf.liveId}',
        isLoading: true,
        isErrorToast: false,
      ).then((res) {
        studioMap = res.data;
        if (studioMap['living_anchor'] != null) {
          avatarImage = studioMap['living_anchor']['avatar'] ?? '';
          anchorName = studioMap['living_anchor']['nickname'] ?? '';
          isShowEvaluateAnchorTipView = SpUtil.getBool(
              SpKeysConstant.is_show_evaluate_anchor_tip_view,
              defValue: true)!;
          if (!haveReview) {
            //是否评价
            haveReview = studioMap['living_anchor']['have_review'] ?? false;
          }
          Get.bottomSheet(
            EvaluateAnchorBottomSheet(
              widget.model.id,
              studioMap,
              isEdit: !haveReview,
            ),
            backgroundColor: Colors.transparent,
            isScrollControlled: true,
          ).then((value) {
            if (value != null) {
              haveReview = value ?? false;
            }
          });
        }
        update();
      });
    } else {
      CustomToast.show("暂时还不能评价哦");
    }
  }
}
